package cn.bdqn.t354.web.filter;

import cn.bdqn.t354.pojo.SysUser;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthorizationFtiler implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //不需要保护的资源直接放行
        String path=request.getRequestURI();
        String content=request.getContextPath();
        System.out.println(path.toString());
        if(path.equals(content+"/login.jsp")){
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //需要保护的资源 判断用户是否登录
        HttpSession session=request.getSession();
        SysUser e=(SysUser)session.getAttribute("loginUser");
        if(e==null){
            //引导用户去登录
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('没有登录；请先去登录(Fiter)');location.href='login.jsp';</script>");
        }else{
            //放行
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
